import React, { Component } from 'react';
import Banner from '../../components/banner'
import Subtitle from '../../components/subtitle'
import TabsCom from '../../components/tabs'
import CourseList from '../../components/course/index'
import CourseTitle from '../../components/coursetitle'
import Teacher from '../../components/teacher'
import { connect } from 'react-redux'
import { actionCreators } from './store'
import Utils from '../../common//utils'
import { removeCart } from '../cart/store/actionCreators'
import { changeShowLogin } from '../../components/header/store/actionCreators'

import { withRouter } from 'react-router-dom'

// import axios from 'axios'
import {
  Container,
  SideBar,
  BarList,
  PhoneWrapper
} from './style'

import { Modal, Button, Input,Tabs  } from 'antd';
const { TabPane } = Tabs;

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tabs: [
        {name: '全部', id: 'all'},
        {name: '即将开始', id: 'soon'},
        {name: '精彩回放', id: 'video'}
      ],
      teacherTabs: [
        {name: '小学', id: '小学'},
        {name: '初中', id: '初中'},
        {name: '高中', id: '高中'}
      ],
      visible: false,
      userName: '',
      password: '',
      showImg: false,
      lessonType: 1
    }
  }
  componentDidMount() {
    // 获取课程
    this.props.getLesson({eduRank: '小学', type: 'all', lessonType: this.state.lessonType})
    this.props.getLesson({eduRank: '初中', type: 'all', lessonType: this.state.lessonType})
    this.props.getLesson({eduRank: '高中', type: 'all', lessonType: this.state.lessonType})
    // 获取老师信息
    this.props.getAllSubject()
    this.props.getTeacher({
      eduRank: '小学',
      subjectId: null
    })
    this.props.getLiveList()
  }
  changeTabs(obj) {
    let str = obj.split('_')[0]
    let type = ""
    switch(str) {
      case 'primary':
        type= '小学'
        break
      case 'junior':
        type = '初中'
        break
      case 'hight':
        type = '高中'
        break
      default:
        type = obj
    }
    this.props.getLesson({
      type: obj.split('_')[1],
      eduRank: type,
      lessonType: this.state.lessonType
    })
  }
  changeTeacherTabs(obj) {
    this.props.getTeacher({
      eduRank: obj.split('_')[1],
      subjectId: ''
    })
  }

  isPhone() {
    var userAgentInfo = navigator.userAgent;
    var Agents = ["Android", "iPhone",
       "SymbianOS", "Windows Phone",
       "iPad", "iPod"];
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
       if (userAgentInfo.indexOf(Agents[v]) > 0) {
          flag = false;
          break;
       }
    }
    return flag;
  }

  cartStatus(params) {
    let status = params.get('shoppingStatus')
    let id = params.getIn(['lesson' ,'id'])
    if(status === '已经购买') {
      this.props.history.push({
        pathname: '/courseitem/' + id
      })
      // window.location.href='/courseitem?id=' + id
    } else if(status === '已加入购物车'){
      this.props.removeCart({
        lessonId: id
      })
    } else if(status === '免费') {
      if(localStorage.getItem('userData')) {
        this.props.history.push({
          pathname: '/courseitem/' + id
        })
      }else {
        this.props.changeLogin(true)
      }
    } else {
      if(localStorage.getItem('userData')) {
        this.props.addCart(id)
      } else {
        this.props.changeLogin(true)
      } 
    }
  }

  renderPhone() {
    return <div style={{backgroundColor: '#fff', position: 'fixed', bottom: '0', top: '0', width: '100%'}}>
      <PhoneWrapper>
        <img src={require('./img/logo.png')} style={{marginTop: '60px'}} />
        <p style={{lineHeight: '4rem', color: '#bfbfbf', textAlign: 'center'}}>新用户请使用pc端注册使用</p>
        <Input placeholder="手机号/身份证" style={{marginTop: '2rem', height: '50px'}} value={this.state.userName} onChange={(e)=> this.setState({userName: e.target.value})}/>
        <Input.Password placeholder="密码" style={{marginTop: '2rem', height: '50px'}} value={this.state.password} onChange={(e)=> this.setState({password: e.target.value})}/>
        <Button type="primary" block style={{marginTop: '2rem', height:'50px'}} onClick={()=> this.props.loginPhone(this.state.userName, this.state.password)}>登录</Button>
      </PhoneWrapper>
    </div>
  }

  renderTabs() {
    return (
      <div>
        <div id="1">
            {/* <CourseTitle name="小学课程"/> */}
            <TabsCom menu={this.state.tabs} type="primary" title="小学课程" nocenter={true}  addCart={(obj) => this.cartStatus.bind(this, obj)} comp={CourseList} list={this.props.primaryList} callback={(obj) => this.changeTabs(obj)}/>
          </div>
          <div id="2">
            {/* <CourseTitle name="初中课程"/> */}
            <TabsCom menu={this.state.tabs} type="junior" title="初中课程" nocenter={true}  addCart={(obj) => this.cartStatus.bind(this, obj)} comp={CourseList} list={this.props.juniorList} callback={(obj) => this.changeTabs(obj)}/>
          </div>
          <div id="3">
            {/* <CourseTitle name="高中课程"/> */}
            <TabsCom menu={this.state.tabs} type="hight" title="高中课程"  nocenter={true} addCart={(obj) => this.cartStatus.bind(this, obj)} comp={CourseList} list={this.props.hightList} callback={(obj) => this.changeTabs(obj)}/>
          </div>
      </div>
    )
  }

  changeBigTabs(obj) {
    this.setState({
      lessonType: obj
    }, ()=> {
      this.props.getLesson({eduRank: '小学', type: 'all', lessonType: obj})
      this.props.getLesson({eduRank: '初中', type: 'all', lessonType: obj})
      this.props.getLesson({eduRank: '高中', type: 'all', lessonType: obj})
    })
  }

  renderPC() {
    return <div>
        <Banner />
        <Container>
          <Subtitle name="今日直播" style={{marginTop: '16px',position: 'relative', left: '8px'}}  icon="icon-sheyingji"/>
          <div className="live clearfix">
            {
              this.props.live.size > 0 ? <CourseList  list={this.props.live} type="live" addCart={(obj)=> this.props.addCart.bind(this, obj)}></CourseList>: <img style={{marginBottom: '20px'}} src={require('./img/live.png')}/>
            }
          </div>
        </Container>
          <div style={{backgroundColor: '#fff', paddingTop: '60px', paddingBottom: '2px'}}>
            <Container>
              <ul className="big-tabs clearfix">
                <li className={this.state.lessonType === 1 ? 'active': ''} onClick={()=> this.changeBigTabs(1)}>
                  公益课程
                </li>
                <li className={this.state.lessonType === 0 ? 'active': ''} onClick={()=> this.changeBigTabs(0)}>
                  培优课程
                </li>
              </ul>
              {this.renderTabs()}
              </Container>
          </div>
          <Container>
            <div id="4">
              <Subtitle name="名师风采" style={{textAlign: 'center', fontWeight: 'normal', marginTop: '15px', fontSize: '30px'}}/>
              <TabsCom menu={this.state.teacherTabs} comp={Teacher} type="teacher" subject = {this.props.subject} callback={(obj) => (this.changeTeacherTabs(obj))} list={this.props.teacherList} getTeacher={(obj) => this.props.getTeacher(obj)} />
            </div>
          </Container>
        <SideBar>
          <BarList>
            <li className="timetable" onClick={()=> this.setState({visible: true})}><a>寒假在线<br/>课程表</a></li>
            <li><a href="#1">小学课程</a></li>
            <li><a href="#2">初中课程</a></li>
            <li><a href="#3">高中课程</a></li>
            <li onMouseEnter={()=> this.setState({showImg: true})} onMouseLeave={()=> this.setState({showImg: false})}>
              {
                this.state.showImg ? <img className="p_code" src={require('./img/code.jpg')}/> : ''
              }
              <a>手机网站</a>
            </li>
            <li style={{backgroundColor: '#999', borderBottom: '2px solid #999'}}><a href="#main">回到顶部</a></li>
          </BarList>
        </SideBar>
        <Modal
          width= {1100}
          visible={this.state.visible}
          onCancel={()=> this.setState({visible: false})}
          footer={null}
        >
          <div style={{textAlign: 'center'}}>
            <img src={require('./img/ke_03.png')}  style={{width: '1000px', borderRadius: '18px', margin: '0 auto'}}/>
          </div>
        </Modal>
    </div>
  }

  checkPage() {
    // let history = useHistory()
    if(!this.isPhone()) {
      return Utils.local('userData') ? this.props.history.push("/phome") : this.renderPhone()
    }else {
      return this.renderPC()
    }
  }
  
  render() {
    return (
      <div>
        {this.checkPage()}
      </div>
    )
  }
}

const mapState = (state) => ({
  primaryList: state.getIn(['home', 'primaryList']),
  juniorList: state.getIn(['home', 'juniorList']),
  hightList: state.getIn(['home', 'hightList']),
  teacherList: state.getIn(['home', 'teacherList']),
  subject: state.getIn(['home', 'subject']),
  login: state.getIn(['header', 'login']),
  live: state.getIn(['home', 'homeLive'])
})

const mapDispatch = (dispatch) => ({
  getLesson(type) {
    dispatch(actionCreators.getLesson(type))
  },
  getAllSubject() {
    dispatch(actionCreators.getAllSubject())
  },
  getTeacher(obj) {
    dispatch(actionCreators.getTeacher(obj))
  },
  addCart(lessonId) {
    dispatch(actionCreators.addCart({
      lessonId
    }))
  },
  loginPhone(u,p) {
    dispatch(actionCreators.loginPhone({
      loginName: u,
      password: p
    }))
  },
  removeCart(params) {
    dispatch(removeCart(params))
  },
  changeLogin(params) {
    dispatch(changeShowLogin(params))
  },
  getLiveList() {
    dispatch(actionCreators.getHomeLive())
  }
})

export default connect(mapState, mapDispatch)(withRouter(Home))